<template>
  <el-dialog
    :title="title"
    :visible="dialogVisible"
    @open="openDialog"
    @close="closeDialog"
    width="500px"
  >
    <el-form :model="form" label-width="80px" ref="formRef" :rules="rules">
      <el-form-item label="任务名称" prop="name">
        <el-input v-model="form.name" autocomplete="off"></el-input>
      </el-form-item>
      <el-form-item label="任务描述" prop="des">
        <el-input v-model="form.des" autocomplete="off"></el-input>
      </el-form-item>
    </el-form>
    <div slot="footer" class="dialog-footer">
      <el-button @click="closeDialog">取 消</el-button>
      <el-button type="primary" @click="submit">确 定</el-button>
    </div>
  </el-dialog>
</template>

<script>
import { fecthAddData, fecthDataInfo, fecthEditData } from '@/api/data-api.js'
import { v4 as uuidv4 } from 'uuid'
export default {
  name: 'AddDialog',
  props: {
    title: {
      type: String
    },
    dialogVisible: {
      type: Boolean
    },
    dataId: {
      type: [String, Number]
    }
  },
  data() {
    return {
      form: {
        name: '',
        des: '',
        id: ''
      },
      rules: {
        name: [{ required: true, message: '任务名称不能为空', trigger: 'blur' }],
        des: [{ required: true, message: '任务描述不能为空', trigger: 'blur' }]
      }
    }
  },
  methods: {
    // 打开duihuak
    async openDialog() {
      if (this.title === '新增数据') {
        this.form.id = uuidv4()
      } else {
        this.form.id = this.dataId
        const { data } = await fecthDataInfo(this.dataId)
        this.form = data
      }
    },
    // 关闭对话框
    closeDialog() {
      this.$emit('close')
    },
    // 点击确定=>兜底验证=>发送数据
    submit() {
      this.$refs.formRef.validate(async valid => {
        if (valid) {
          if (this.title === '新增数据') {
            await fecthAddData(this.form)
          } else {
            await fecthEditData(this.form)
          }

          this.$message.success(`${this.title}成功`)
          this.$refs.formRef.resetFields()
          this.$emit('close')
          this.$emit('add-success')
        }
      })
    }
  }
}
</script>

<style lang="less" scoped></style>
